﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using web.Models;
using web.Common;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using System.Text;

namespace web.BLL
{
    public class sitebll
    {
        public static userinfo getUser(string username, string pwd) {
            using (qydataEntities sce = new qydataEntities()) {
                userinfo user=sce.userinfo.FirstOrDefault(t=>t.loginname==username&&t.password==pwd);
                if (user != null)
                {
                    user.logindate = DateTime.Now;
                    user.loginip = GetClientIp();
                    sce.SaveChanges();
                }
                return user;

            }
        }

        public static String GetClientIp()
        {
            String clientIP = "";
            if (System.Web.HttpContext.Current != null)
            {
                clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(clientIP) || (clientIP.ToLower() == "unknown"))
                {
                    clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];
                    if (string.IsNullOrEmpty(clientIP))
                    {
                        clientIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                }
                else
                {
                    clientIP = clientIP.Split(',')[0];
                }
            }
            return clientIP;
        }  
        public static Boolean addlog(string info) {
            using (qydataEntities sce = new qydataEntities())
            {
                userinfo u = (userinfo)HttpContext.Current.Session["User"];
                log l = new log();
                l.info = info;
                l.userid = u.id;
                l.ip = GetClientIp();
                l.loginname = u.loginname;
                l.adddate = DateTime.Now;
                try
                {
                    sce.AddTolog(l);
                    sce.SaveChanges();
                    return true;
                }
                catch {
                    return false;
                }
                    
            }
        
        }

        public static String addorupdatenews(int id)
        {

            using (qydataEntities sce = new qydataEntities())
            {
                if (id > 0)
                {
                    newsinfo model = sce.newsinfo.FirstOrDefault(t => t.id == id);
                    if (model == null)
                    {
                        model = new newsinfo();
                        ReflectionForm.GetData<newsinfo>(model);
                        sce.newsinfo.AddObject(model);
                    }
                    else
                    {
                        ReflectionForm.GetData<newsinfo>(model);
                    }
                }
                else
                {
                    newsinfo model = new newsinfo();
                    ReflectionForm.GetData<newsinfo>(model);
                    sce.newsinfo.AddObject(model);
                }
                if (sce.SaveChanges() > 0)
                {
                    return "{\"success\":true}";
                }
                else
                {
                    return "{\"success\":false}";
                }
            }
        }


        public static newsinfo getnews(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                newsinfo model = sce.newsinfo.FirstOrDefault(t => t.id == id);
                return model;
            }
        }
        public static string JsonHelper(string json, string format)
        {
            return Regex.Replace(json, @"\\/Date\((\d+)\)\\/", match =>
            {
                DateTime dt = new DateTime(1970, 1, 1);
                dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                dt = dt.ToLocalTime();
                return dt.ToString(format);
            });
        }

        public static string getnewslist(int typeid,string keyword,int start,int limit) {
            using (qydataEntities sce = new qydataEntities())
            {
                var list = sce.newsinfo.Where(t => t.typeid == typeid);
                if (keyword != "") {

                    list = list.Where(t=>t.title.Contains(keyword));
                }
                int allcount = list.Count();
                List<newsinfo> result = list.Select(d => d).OrderByDescending(d => d.id).Skip(start).Take(limit).ToList();
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                return "{\"total\": " + allcount + ", \"data\": " + JsonHelper(serializer.Serialize(result), "yyyy-MM-dd") + " }";
            }
        
        }


        internal static void delnews(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                newsinfo model = sce.newsinfo.FirstOrDefault(t => t.id == id);
                sce.DeleteObject(model);
                sce.SaveChanges();
            }
        }

        internal static void delnews(string ids)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (ids.Trim(',') != "")
                {
                    for (int i = 0; i < ids.Trim(',').Split(',').Length; i++)
                    {
                        if (ids.Trim(',').Split(',')[i] != "")
                        {
                            int id = Convert.ToInt32(ids.Trim(',').Split(',')[i]);
                            newsinfo model = sce.newsinfo.FirstOrDefault(t => t.id == id);
                            sce.DeleteObject(model);
                        }
                    }
                    sce.SaveChanges();
                }
              
                
            }
        }

        internal static String savesite(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (id > 0)
                {
                    siteinfo model = sce.siteinfo.FirstOrDefault(t => t.id == id);
                    if (model == null)
                    {
                        model = new siteinfo();
                        ReflectionForm.GetData<siteinfo>(model);
                        sce.siteinfo.AddObject(model);
                    }
                    else
                    {
                        ReflectionForm.GetData<siteinfo>(model);
                    }
                }
                else
                {
                    siteinfo model = new siteinfo();
                    ReflectionForm.GetData<siteinfo>(model);
                    sce.siteinfo.AddObject(model);
                }
                if (sce.SaveChanges() > 0)
                {
                    return "{\"success\":true}";
                }
                else
                {
                    return "{\"success\":false}";
                }
            }
        }

        internal static siteinfo getsite(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                siteinfo model = sce.siteinfo.FirstOrDefault(t => t.id == id);
                return model;
            }
        }

        internal static string getloglist(string keyword, int start, int limit)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                var list = sce.log.AsQueryable();
                if (keyword != "")
                {
                    list = list.Where(t => t.info.Contains(keyword));
                }
                int allcount = list.Count();
                List<log> result = list.Select(d => d).OrderByDescending(d => d.id).Skip(start).Take(limit).ToList();
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                return "{\"total\": " + allcount + ", \"data\": " + JsonHelper(serializer.Serialize(result), "yyyy-MM-dd hh:mm:ss") + " }";
            }
        
        }

        internal static void dellogs(string ids)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (ids.Trim(',') != "")
                {
                    for (int i = 0; i < ids.Trim(',').Split(',').Length; i++)
                    {
                        if (ids.Trim(',').Split(',')[i] != "")
                        {
                            int id = Convert.ToInt32(ids.Trim(',').Split(',')[i]);
                            log model = sce.log.FirstOrDefault(t => t.id == id);
                            sce.DeleteObject(model);
                        }
                    }
                    sce.SaveChanges();
                }


            }
        }

        internal static string getbanerlist(int start, int limit)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                var list = sce.sitebaner.AsQueryable();
                int allcount = list.Count();
                List<sitebaner> result = list.Select(d => d).OrderByDescending(d => d.id).Skip(start).Take(limit).ToList();
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                return "{\"total\": " + allcount + ", \"data\": " + serializer.Serialize(result) + " }";
            }
        }

        internal static void delbaners(string ids)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (ids.Trim(',') != "")
                {
                    for (int i = 0; i < ids.Trim(',').Split(',').Length; i++)
                    {
                        if (ids.Trim(',').Split(',')[i] != "")
                        {
                            int id = Convert.ToInt32(ids.Trim(',').Split(',')[i]);
                            sitebaner model = sce.sitebaner.FirstOrDefault(t => t.id == id);
                            sce.DeleteObject(model);
                        }
                    }
                    sce.SaveChanges();
                }


            }
        }

        internal static object savebaner(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (id > 0)
                {
                    sitebaner model = sce.sitebaner.FirstOrDefault(t => t.id == id);
                    if (model == null)
                    {
                        model = new sitebaner();
                        ReflectionForm.GetData<sitebaner>(model);
                        sce.sitebaner.AddObject(model);
                    }
                    else
                    {
                        ReflectionForm.GetData<sitebaner>(model);
                    }
                }
                else
                {
                    sitebaner model = new sitebaner();
                    ReflectionForm.GetData<sitebaner>(model);
                    sce.sitebaner.AddObject(model);
                }
                if (sce.SaveChanges() > 0)
                {
                    return "{\"success\":true}";
                }
                else
                {
                    return "{\"success\":false}";
                }
            }
        }

        internal static sitebaner getbaner(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                sitebaner model = sce.sitebaner.FirstOrDefault(t => t.id == id);
                return model;
            }
        }

        internal static string getuserlist(int start, int limit)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                var list = sce.userinfo.AsQueryable();
                int allcount = list.Count();
                List<userinfo> result = list.Select(d => d).OrderByDescending(d => d.id).Skip(start).Take(limit).ToList();
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                return "{\"total\": " + allcount + ", \"data\": " + JsonHelper(serializer.Serialize(result), "yyyy-MM-dd hh:mm:ss") + " }";
            }
        }

        internal static void delusers(string ids)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (ids.Trim(',') != "")
                {
                    for (int i = 0; i < ids.Trim(',').Split(',').Length; i++)
                    {
                        if (ids.Trim(',').Split(',')[i] != "")
                        {
                            int id = Convert.ToInt32(ids.Trim(',').Split(',')[i]);
                            userinfo model = sce.userinfo.FirstOrDefault(t => t.id == id);
                            sce.DeleteObject(model);
                        }
                    }
                    sce.SaveChanges();
                }


            }
        }

        internal static object saveuser(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (id > 0)
                {
                    userinfo model = sce.userinfo.FirstOrDefault(t => t.id == id);
                    if (model == null)
                    {
                        model = new userinfo();
                        ReflectionForm.GetData<userinfo>(model);
                        sce.userinfo.AddObject(model);
                    }
                    else
                    {
                        ReflectionForm.GetData<userinfo>(model);
                    }
                }
                else
                {
                    userinfo model = new userinfo();
                    ReflectionForm.GetData<userinfo>(model);
                    sce.userinfo.AddObject(model);
                }
                if (sce.SaveChanges() > 0)
                {
                    return "{\"success\":true}";
                }
                else
                {
                    return "{\"success\":false,\"msg\":\"保存失败\"}";
                }
            }
        }

        internal static userinfo getuser(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                userinfo model = sce.userinfo.FirstOrDefault(t => t.id == id);
                return model;
            }
        }

        internal static bool isexit(string loginname)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                userinfo model = sce.userinfo.FirstOrDefault(t => t.loginname == loginname);
                return model==null;
            }
        }


        internal static string gettypelist(int start, int limit)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                List<newstype> list = sce.newstype.ToList();
                int allcount = list.Count();
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                List<newstype> firstlevel = list.Where(t => t.parentid == 0).ToList();
                StringBuilder str = new StringBuilder();
                foreach (newstype t in firstlevel) {

                    str.Append("{\"id\":" + t.id + ",\"typename\":\"" + t.typename + "\",\"parentid\":" + t.parentid + ",\"parentids\":\"" + t.parentids + "\"" + getdeepnode(t.id, list) + "},");
                }
                return "{\"total\": " + allcount + ", \"data\": [" + str.ToString().TrimEnd(',') + "] }";
            }
        }

        private static string getdeepnode(int p, List<newstype> list)
        {
            List<newstype> level = list.Where(t => t.parentid == p).ToList();
            if (level.Count > 0)
            {
                StringBuilder str = new StringBuilder();
                foreach (newstype t in level)
                {
                    str.Append("{\"id\":" + t.id + ",\"typename\":\"" + t.typename + "\",\"parentid\":" + t.parentid + ",\"parentids\":\"" + t.parentids + "\"" + getdeepnode(t.id, list) + "},");
                }
                return ",\"children\":[" + str.ToString().TrimEnd(',') + "]";
            }
            else {
                return "";
            
            }

        }

        internal static void deltypes(string ids)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (ids.Trim(',') != "")
                {
                    for (int i = 0; i < ids.Trim(',').Split(',').Length; i++)
                    {
                        if (ids.Trim(',').Split(',')[i] != "")
                        {
                            int id = Convert.ToInt32(ids.Trim(',').Split(',')[i]);
                            newstype model = sce.newstype.FirstOrDefault(t => t.id == id);
                            sce.DeleteObject(model);
                        }
                    }
                    sce.SaveChanges();
                }


            }
        }

        internal static object savetype(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                if (id > 0)
                {
                    newstype model = sce.newstype.FirstOrDefault(t => t.id == id);
                    if (model == null)
                    {
                        model = new newstype();
                        ReflectionForm.GetData<newstype>(model);
                        sce.newstype.AddObject(model);
                    }
                    else
                    {
                        ReflectionForm.GetData<newstype>(model);
                    }
                }
                else
                {
                    newstype model = new newstype();
                    ReflectionForm.GetData<newstype>(model);
                    sce.newstype.AddObject(model);
                }
                if (sce.SaveChanges() > 0)
                {
                    return "{\"success\":true}";
                }
                else
                {
                    return "{\"success\":false,\"msg\":\"保存失败\"}";
                }
            }
        }

        internal static newstype gettype(int id)
        {
            using (qydataEntities sce = new qydataEntities())
            {
                newstype model = sce.newstype.FirstOrDefault(t => t.id == id);
                return model;
            }
        }


      
    }
}